package com.hxc.springboot.judge;

import cn.hutool.json.JSONUtil;
import com.hxc.springboot.common.ErrorCode;
import com.hxc.springboot.exception.BusinessException;
import com.hxc.springboot.judge.JudgeStrategy.JudgeContext;
import com.hxc.springboot.judge.JudgeStrategy.JudgeManager;
import com.hxc.springboot.judge.codesandbox.CodeSandbox;
import com.hxc.springboot.judge.codesandbox.CodeSandboxFactory;
import com.hxc.springboot.judge.codesandbox.CodeSandboxProxy;
import com.hxc.springboot.judge.codesandbox.model.ExecuteCodeRequest;
import com.hxc.springboot.judge.codesandbox.model.ExecuteCodeResponse;
import com.hxc.springboot.model.dto.question.JudgeCase;
import com.hxc.springboot.model.dto.questionsubmit.JudgeInfo;
import com.hxc.springboot.model.entity.Question;
import com.hxc.springboot.model.entity.QuestionSubmit;
import com.hxc.springboot.model.enums.QuestionSubmitStatusEnum;
import com.hxc.springboot.service.QuestionService;
import com.hxc.springboot.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Value("${codeSandbox.type}")
    private String type;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {

        System.out.println("doJudge方法调用！");
        // 1）传入题؜目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        Long id = questionSubmit.getId();
        Question question = questionService.getById(questionSubmit.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }

        // 2）如果题目提交状态不为等待中，就不用重复执行了
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题中");
        }
        QuestionSubmit submit = new QuestionSubmit();
        submit.setId(id);
        submit.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean result = questionSubmitService.updateById(submit);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目状态更新错误");
        }
        // 3）调用代码沙箱
        // 静态工厂获取代码沙箱实例
        CodeSandbox codeSandBox = CodeSandboxFactory.newInstance(type);
        // 动态代理增加日志
        codeSandBox = new CodeSandboxProxy(codeSandBox);
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        // 获取测试用例
        List<JudgeCase > judgeCaseList = JSONUtil.toList(question.getJudgeCase(), JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest request = new ExecuteCodeRequest(inputList, code, language);
        // 执行代码
        ExecuteCodeResponse response = codeSandBox.executeCode(request);
        List<String> outputList = response.getOutputList();

        // 根据沙箱的执行结果，设置题目的判题状态和信息
        JudgeContext judgeContext = JudgeContext.builder().judgeInfo(response.getJudgeInfo())
                .inputList(inputList)
                .outputList(outputList)
                .judgeCaseList(judgeCaseList)
                .question(question)
                .questionSubmit(questionSubmit)
                .build();
        JudgeManager judgeManager = new JudgeManager();
        // 策略模式简化调用
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        // 修改数据库判题结果
        submit.setId(id);
        submit.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        submit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        result = questionSubmitService.updateById(submit);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目状态更新错误");
        }
        return questionSubmitService.getById(id);
    }
}
